import { computed, defineComponent, inject, ref } from 'vue'
import useMemo from '../_util/hooks/useMemo'
import { radioGroupContext } from './Group'

export const RadioProps = {
  prefixCls: { default: 'x-radio' },
  checked: Boolean,
  disabled: Boolean,
  name: String,
  value: [String, Number]
}

export default defineComponent({
  name: 'x-radio',
  props: RadioProps,
  emits: ['update:checked', 'change'],
  setup(props, { emit, slots }) {
    const groupContext = inject(radioGroupContext)
    const disabled = useMemo(() => groupContext?.disabledRef?.value || props.disabled)
    const name = useMemo(() => groupContext?.nameRef?.value || props.name)
    const checked = useMemo(() => props.checked)

    const _checked = computed(() => {
      if (groupContext) return groupContext.valueRef.value == (props.value as string)
      return checked.value
    })

    function onChange(e: Event) {
      if (props.disabled) return
      if (groupContext) {
        groupContext.onChange(props.value)
      } else {
        // @ts-ignore
        const val = e.target.checked
        checked.value = val
        emit('update:checked', val)
      }
      emit('change', props.value)
    }

    const focused = ref(false)
    function onFocus() {
      focused.value = true
    }
    function onBlur() {
      focused.value = false
    }

    return () => {
      const { prefixCls } = props
      const radioProps = {
        class: [
          prefixCls,
          {
            [`${prefixCls}-checked`]: _checked.value,
            [`${prefixCls}-focused`]: focused.value,
            [`${prefixCls}-disabled`]: disabled.value
          }
        ]
      }

      const inputProps = {
        class: `${prefixCls}_input`,
        name: name.value,
        value: props.value,
        type: 'radio',
        checked: !!_checked.value,
        disabled: disabled.value,
        onFocus,
        onBlur,
        onChange
      }

      return (
        <label {...radioProps}>
          <input {...inputProps} />
          <div class={`${prefixCls}_dot`}></div>
          <div class={`${prefixCls}_label`}>{slots.default?.()}</div>
        </label>
      )
    }
  }
})
